package com.cgsd.heyu.ui.login;

import android.app.Activity;
import android.content.Intent;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.android.library.utils.AppManager;
import com.android.library.utils.LogUtils;
import com.android.library.utils.SharedPreferencesHelper;
import com.android.library.utils.StringUtils;
import com.android.library.utils.ToastHelper;
import com.cgsd.heyu.BuildConfig;
import com.cgsd.heyu.R;
import com.cgsd.heyu.api.ApiService;
import com.cgsd.heyu.api.AppConfig;
import com.cgsd.heyu.common.AppMobclickAgent;
import com.cgsd.heyu.common.Constants;
import com.cgsd.heyu.common.Helper;
import com.cgsd.heyu.common.UserModeConfig;
import com.cgsd.heyu.http.BaseResponse;
import com.cgsd.heyu.http.BaseRxSubscribe;
import com.cgsd.heyu.http.ErrorMessage;
import com.cgsd.heyu.http.RetrofitServiceManagerPhp;
import com.cgsd.heyu.http.RxjavaHelper;
import com.cgsd.heyu.presenter.user.UserContract;
import com.cgsd.heyu.presenter.user.UserPresenter;
import com.cgsd.heyu.ui.BaseActivity;
import com.cgsd.heyu.ui.common.TabActivity;
import com.cgsd.heyu.ui.webview.CommonH5Activity;
import com.cgsd.heyu.utils.DeviceUtils;
import com.cgsd.heyu.utils.RequestParams;
import com.cgsd.heyu.utils.StatusBarUtil;
import com.cgsd.heyu.widgets.dialog.AgreementDialog;
import com.hztz.kankanzhuan.KanNewsSDK;
import com.hztz.kankanzhuan.listener.LoginCallListener;

import okhttp3.RequestBody;

/**
 * @author xiaoxing
 * Description 登录注册
 * CreateData: 2020/11/2
 */
public class LoginActivity extends BaseActivity<UserContract.Presenter> implements View.OnClickListener, TextWatcher, UserContract.LoginView {
    /**
     * 倒计时（60s）
     */
    private final long MILLISINFUTURE = 60 * 1000;
    /**
     * //步长（1s）
     */
    private final long COUNTDOWNINTERVAL = 1000;
    private CountDownTimer timer;
    private EditText edtPhone;
    private TextView btnGetInto;
    private CheckBox mCheckBox;
    private AgreementDialog agreementDialog;
    private EditText edtInterviewCode;
    private EditText edtPassword;
    private String password;
    private String phone;
    private String deviceId;


    public static void actionStart(Activity activity) {
        /**
         * 到达此页面可清空用户相关数据和关闭所有页面
         */
        AppMobclickAgent.onEvent(AppMobclickAgent.DENGLUYE);
        Intent intent = new Intent(activity, LoginActivity.class);
        activity.startActivity(intent);
        Helper.saveTokenInfo("");
        Helper.saveTokenPhpInfo("");
        UserModeConfig.setUserModeConfig(null);
        AppManager.getAppManager().finishAllActivity();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        new UserPresenter(this);
        edtPhone = findViewById(R.id.edt_phone);
        btnGetInto = findViewById(R.id.tv_get_into);
        mCheckBox = findViewById(R.id.mCheckBox);
        edtInterviewCode = findViewById(R.id.edt_interview);
        edtPassword = findViewById(R.id.edt_password);

        btnGetInto.setOnClickListener(this);
        findViewById(R.id.tv_privacy_agreement).setOnClickListener(this);
        findViewById(R.id.tv_user_agreement).setOnClickListener(this);
        edtPhone.addTextChangedListener(this);
        edtPassword.addTextChangedListener(this);
        findViewById(R.id.tv_register).setOnClickListener(this);
        findViewById(R.id.tv_forget_password).setOnClickListener(this);
        deviceId = DeviceUtils.getUniqueId(this);
        showAgreementDialog();
    }

    @Override
    protected void initData() {

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_get_into:
                AppMobclickAgent.onEvent(AppMobclickAgent.DENGLU_JINRU);
                if (mCheckBox.isChecked()) {
                    if (DeviceUtils.isSimulator(this)) { // 这里把模拟器尽调
                        showToast("暂不支持此设备");
                        return;
                    }
                    showCommonSubmitDialog("");
                    mPresenter.userLogin(phone, password, deviceId);
                } else {
                    showToast(getString(R.string.login_no_agreement_tips));
                }
                break;
            case R.id.tv_user_agreement:
                //用户协议
                CommonH5Activity.actionStart(this, AppConfig.USER_AGREEMENT, getString(R.string.user_agreement));
                break;
            case R.id.tv_privacy_agreement:
                //隐私协议
                CommonH5Activity.actionStart(this, AppConfig.PRIVACY_PROTOCOL, getString(R.string.privacy_agreement));
                break;
            case R.id.tv_send_code:
                String phone = edtPhone.getText().toString();
                if (StringUtils.isMobileNo(phone)) {
                    showCommonSubmitDialog("");
                    mPresenter.getVerificationCode(phone, "1");
                } else {
                    showToast(getString(R.string.toast_phone_error));
                }
                break;
            case R.id.tv_register:
                RegisterActivity.actionStart(this);
                break;
            case R.id.tv_forget_password:
                ForgetPasswordActivity.actionStart(this);
                break;
            default:
        }
    }


    /**
     * 刷新登录进入按钮样式
     */
    private void refreshBtn() {
        phone = edtPhone.getText().toString();
        password = edtPassword.getText().toString();
        if (StringUtils.isMobileNo(phone) && StringUtils.isNotEmpty(password)) {
            btnGetInto.setEnabled(true);
        } else {
            btnGetInto.setEnabled(false);
        }
    }

    @Override
    protected void setStatusBar() {
        StatusBarUtil.fullBar(this);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        refreshBtn();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
    }

    /**
     * 跳转下个界面处理
     */
    private void nextActivity() {
        if (StringUtils.isEmpty(UserModeConfig.getInstance().headImgUrl)) {
            //没有选择图像，跳转选择图像页面
            AvatarSelectActivity.actionStart(this, AvatarSelectActivity.CREATE_AVATAR);
        } else {
            startActivity(TabActivity.getIntent(this));
        }
        finish();
    }

    /**
     * 显示服务协议政策
     */
    private void showAgreementDialog() {
        boolean isAgree = SharedPreferencesHelper.getBoolean(Constants.ShareKeyValue.IS_AGREE_AGREEMENT);
        if (isAgree) {
            return;
        }
        if (agreementDialog == null) {
            agreementDialog = new AgreementDialog(this);
            agreementDialog.setConfirmListener(new AgreementDialog.ConfirmListener() {
                @Override
                public void doConfirm() {
                    agreementDialog.dismiss();
                    SharedPreferencesHelper.put(Constants.ShareKeyValue.IS_AGREE_AGREEMENT, true);
                }

                @Override
                public void doCancel() {
                    agreementDialog.dismiss();
                    finish();
                }
            });
        }
        agreementDialog.show();
    }

    @Override
    public void codeSuccess() {
        dismissCommonSubmitDialog();
        ToastHelper.showDefaultToast("发送成功");
        timer.start();
    }

    @Override
    public void loginSuccess(UserModeConfig userModeConfig) {
        SharedPreferencesHelper.put(Constants.ShareKeyValue.NEW_USER, userModeConfig.loginOrRegister);
        dismissCommonSubmitDialog();
        kanNewsLogin(UserModeConfig.getInstance().userId);
//        nextActivity();
        refreshPhpToken();
    }

    private void kanNewsLogin(String userId) {

        KanNewsSDK.getInstance().login(AppConfig.NEWS_KEY, userId, new LoginCallListener() {
            @Override
            public void onSuccess() {
                com.apkfuns.logutils.LogUtils.e(TAG + "kanNewsLogin success");
            }

            @Override
            public void onFailed(int i, String s) {
                com.apkfuns.logutils.LogUtils.e(TAG + "kanNewsLogin" + i + " = " + s);
            }
        });
    }

    /**
     * refresh token
     */
    private void refreshPhpToken() {
        RequestBody requestBody = new RequestParams().putUid().get();
        RetrofitServiceManagerPhp.getInstance().creat(ApiService.class)
                .refreshToken(requestBody)
                .compose(RxjavaHelper.observeOnMainThread())
                .subscribe(new BaseRxSubscribe<BaseResponse<String>>() {
                    @Override
                    public void onSuccess(BaseResponse<String> baseResponse) {
                        Helper.saveTokenPhpInfo(baseResponse.getBizBody());
                        LogUtils.i("sky", baseResponse.getBizBody());
                        nextActivity();
                    }

                    @Override
                    public void onError(ErrorMessage error) {
                    }
                });
    }
}
